<script lang="ts" setup>
import { ref, unref } from "vue"
import { SysUser } from "@/api/user/type/user"
import RoleTree from "../role/role-tree.vue"
import ImageUpload from "@/components/Upload/image-upload.vue"
import { userAddApi } from "@/api/user/user"
import { ElMessage } from "element-plus"

const dialogVisible = ref(false)
const emits = defineEmits(["saveAfter"])
const user = ref<SysUser>({
  roleIds: [] as string[]
} as SysUser)

const openDialog = () => {
  dialogVisible.value = true
}

const onSubmit = () => {
  userAddApi({ adminUser: unref(user) })
    .then((res) => {
      const { code } = res
      if (code === 200) {
        ElMessage({
          type: "success",
          message: "新增成功！"
        })
        dialogVisible.value = false
        user.value = {
          roleIds: [] as string[]
        } as SysUser
      }
    })
    .finally(() => {
      emits("saveAfter")
    })
}

const fPid = (ids: string[]) => {
  user.value.roleIds = ids
}

defineExpose({ openDialog })
</script>

<template>
  <el-drawer v-model="dialogVisible" title="I am the title" :with-header="false">
    <el-form v-if="user" :model="user">
      <el-form-item label="账号">
        <el-input v-model="user.username" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="user.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="user.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="角色">
        <RoleTree @fPid="fPid" />
      </el-form-item>
      <el-form-item label="头像">
        <ImageUpload />
      </el-form-item>
      <el-form-item label="简介">
        <el-input v-model="user.intro" maxlength="30" placeholder="简介" show-word-limit type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提 交</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
